package com.guojian.common.http;

import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;

import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestTemplate;

import com.google.common.collect.Maps;

public class RestTemplateClient {

	public static <T> ResponseEntity<T> execute(HttpConfig httpConfig, Class<T> responseType) {
		if (httpConfig.getRequestBody() != null && httpConfig.getHttpMethod() == HttpMethod.GET) {
			throw new IllegalArgumentException("请求类型错误!");
		}
		RestTemplate restTemplate = new RestTemplateBuilder().requestFactory(httpConfig.getRequestFactory()).build();

		List<HttpMessageConverter<?>> messageConverterList = restTemplate.getMessageConverters();
		for (HttpMessageConverter<?> httpMessageConverter : messageConverterList) {
			if (httpMessageConverter instanceof StringHttpMessageConverter) {
				StringHttpMessageConverter stringHttpMessageConverter = (StringHttpMessageConverter) httpMessageConverter;
				stringHttpMessageConverter.setDefaultCharset(StandardCharsets.UTF_8);
			}
		}

		HttpEntity<?> requestEntity = new HttpEntity<>(httpConfig.getRequestBody(), httpConfig.getHttpHeaders());
		return restTemplate.exchange(httpConfig.getUrl(), httpConfig.getHttpMethod(), requestEntity, responseType);
	}

	public static void main(String[] args) {
		/*HttpConfig config = HttpConfig.defaultConfig().post().setUrl("http://localhost:9080/ccbhousing").addJsonParams("name", "guojian");
		String aaa = RestTemplateClient.execute(config, String.class).getBody();
		System.out.println(aaa);*/

		Map<String, Object> maps = Maps.newConcurrentMap();
		maps.put("name", "guojian");

		Map<String, Object> maps1 = Maps.newConcurrentMap();

		maps1.put("name1", "guojian1");

		//json
		HttpConfig config = HttpConfig.defaultConfig().addJsonParams(maps).addJsonParams(maps1).post("http://localhost:8027/forwordall");

		//HttpConfig config = HttpConfig.defaultConfig().setRequestBody("guojian").post("http://localhost:8027/forwordall");

		String response = RestTemplateClient.execute(config, String.class).getBody();

		System.out.println(response);
		
		
		

	}

}
